import { createRouter, createWebHistory } from "vue-router";
import Cookies from "js-cookie";
import useUserInfoStore from "@/stores/useInfo";
import * as admin from "@/request/modules/admin";
import type { RouteRecordRaw } from "vue-router";
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
    },
    {
      path: "/",
      redirect: "/home",
      component: () => import("@/views/Layout.vue"),
      children: [
        {
          path: "/home",
          component: () => import("@/views/home/home.vue"),
          meta: {
            secondRouteName: "首页",
          },
        },
      ],
    },
  ],
});

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  let token = Cookies.get("token");
  const userInfoStore = useUserInfoStore();
  const username = userInfoStore.username;

  if (token && !username) {
    try {
      const adminInfo = await admin.LoginInfoAPI();
      userInfoStore.updateUserInfo(adminInfo.menus, adminInfo.username);
      userInfoStore.filterMenus.forEach((el) => {
        let dynamicRouters: RouteRecordRaw = {
          path: "/" + el.name,
          component: () => import("../views/Layout.vue"),
          children: [],
        };
        // 二级路由
        if (el.children?.length) {
          el.children.forEach((item) => {
            dynamicRouters.children?.push({
              path: item.name,
              component: () => import(`../views/${el.name}/${item.name}.vue`),
              meta: {
                primaryRoutePath: "/" + el.name,
                primaryRouteName: el.title,
                secondRouteName: item.title,
              },
            });
          });
          dynamicRouters.redirect = "/" + el.name + "/" + el.children[0].name;
        }
        router.addRoute(dynamicRouters);
      });
      next(to.path);
    } catch (e) {
      Cookies.remove("token");
      next("/login");
    }
  } else if (token && to.fullPath === "/login") {
    next(from.fullPath);
  } else if (!token && to.fullPath !== "/login") {
    next("/login");
  } else {
    next();
  }
});
export default router;
